<?php
/**
 * 微信发送消息
 * User: Acer
 * Date: 2022/7/24
 * Time: 11:50
 */
namespace app\wx\controller;
use app\core\MyController;
use app\wx\service\GzhSendMsgService;
use think\Log;

class WxSendMsg extends MyController
{
    protected $noNeedAction = ['*']; // 不需要校验控制器，通道
    // 操作前置
    protected $beforeActionList = ['my_initialize'];

    // 操作前置方法
    public function my_initialize()
    {

    }

    // 接受用户首次关注公众号
    public function first_follow_gzh(){
          Log::record("关注公粽号");
         $xml_str = file_get_contents("php://input");
             Log::info("============= 有没有接收到 ===============");
        if(empty($xml_str)) die('');
        Log::info("============= 接受用户首次关注公众号 ===============");
        // 接收的数据流是xml数据格式
        // 解析该xml字符串，利用simpleXML
        libxml_disable_entity_loader(true);
        //禁止xml实体解析，防止xml注入
        $request_xml = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);
        Log::info($request_xml);
        $GzhSendMsgService = new GzhSendMsgService();
        //判断该消息的类型，通过元素MsgType
        switch ($request_xml->MsgType){
            case 'event':
                //判断具体的时间类型（关注、取消、点击）
                $event = $request_xml->Event;
                if ($event=='subscribe') { // 关注事件
                    Log::info("===============关注事件=============");
                   $msgList = $GzhSendMsgService->get_gzh_msg();
                    if(count($msgList) > 0){
                        foreach($msgList as $key=>$value){
                            // 客服发送消息
                            $this->kefu_send_msg($request_xml->FromUserName,stripcslashes($value));
                            // 另一种文本推送的方式发送消息
//                            $this->send_text($request_xml,stripcslashes($value));
                        }
                    }else{
                        exit();
                    }
                }elseif ($event=='CLICK') {//菜单点击事件

                }elseif ($event=='VIEW') {//连接跳转事件

                }else{

                }
                break;
            case 'text'://文本消息
                exit();
                break;
            case 'image'://图片消息
                break;
            case 'voice'://语音消息
                break;
            case 'video'://视频消息
                break;
            case 'shortvideo'://短视频消息
                break;
            case 'location'://位置消息
                break;
            case 'link'://链接消息
                break;
        }


    }

    // 暴露接口
    public function send_kefu_msg(){
        $query = input();
        if(empty($query['open_id']) || empty($query['send_text'])) json_err(-210,['参数缺失！']);
        return  $this->kefu_send_msg($query['open_id'],stripcslashes($query['send_text']));
    }

    // 客服发送消息
    protected function kefu_send_msg($to_openid= null,$content = null){
        
           Log::info("============= 客服发送消息 222222===============");
        
        if(empty($to_openid) || empty($content)) return false;
        $Authorize =  new Authorize();
        $Token = $Authorize->get_token();
        $url =config("gzh_send_url").$Token;
        $data = '{
          "touser":"'.$to_openid.'",
          "msgtype":"text",
          "text":{
            "content":"'.$content.'"
          }
         }';
        $res = send_request($url,'POST',$data);
        $res = (array)json_decode($res);
        return $res;
    }

    // 文本消息 【 调用： $this->send_text($request_xml,stripcslashes($value));】
    protected function send_text($request_xml,$content="欢迎关注E行销健康公众号"){
        //回复用户消息(纯文本格式)
        $toUser = $request_xml->FromUserName;
        $fromUser = $request_xml->ToUserName;
        $time = time();
        $msgType = 'text';
        $template = "<xml>
                         <ToUserName><![CDATA[%s]]></ToUserName>
                         <FromUserName><![CDATA[%s]]></FromUserName>
                         <CreateTime>%s</CreateTime>
                         <MsgType><![CDATA[%s]]></MsgType>
                         <Content><![CDATA[%s]]></Content>
                         </xml>";
        $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
        echo $info;
    }

    // 发送模板消息
    public function send_gzh_template_message(){
        $data = input();
        if(empty($data['type']) || empty($data['openId']) || empty($data['send_data'])) return false;
        $data['send_data'] = (array)json_decode($data['send_data']);
        if((int)$data['type'] == 1){ // 发送预约审核模板消息[用户接收]
            // 获取模板数据
            $template_data = $this->wx_gzh_examine_template($data['openId'],$data['send_data']);
            // 发送消息
            return $this->send_template_message($template_data);
        }else if((int)$data['type'] == 2){ // 客户预约通知【管理员接收】
            // 获取模板数据
            $template_data = $this->wx_gzh_admin_examine_template($data['openId'],$data['send_data']);
            // 发送消息
            return $this->send_template_message($template_data);

        }
    }

    // 发送消息
    public function send_template_message($send_template_data){
        $Authorize =  new Authorize();
        $Token = $Authorize->get_token();
        $url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$Token;
        $json_template = json_encode($send_template_data);
        $res_data = curlPost($url,urldecode($json_template));
        $res_data = json_decode($res_data, true);
        return $res_data;
    }

    // 预约审核结果通知【用户接收】
    public function wx_gzh_examine_template($openId,$data){
        if(empty($openId) || !isset($data['name']) ||!isset($data['mobile'])||!isset($data['subscribe_date'])||!isset($data['examine_text'])||!isset($data['examine_reason'])||!isset($data['remark']) ) return false;
        $template = [
            "touser" => "$openId",
             "template_id" => config('wx_gzh_examine_template_id'),
             'url' =>"https://archives.e-xingxiao.cn/index.php/web/wxLogin",
             'topcolor' => '#CCCCCC',
             'data' => [
                 'first'   => [
                     'value' =>urlencode('亲，预约审核结果通知如下：'),
                     'color' =>'#333333'
                 ],
                 // 用户姓名
                 'keyword1' => [
                     'value' =>urlencode($data['name']),
                     'color' =>'#333333'
                 ],
                 // 用户手机
                 'keyword2' => [
                     'value' =>urlencode($data['mobile']),
                     'color' =>'#333333'
                 ],
                // 预约时间
                'keyword3' => [
                    'value' =>urlencode($data['subscribe_date']),
                    'color' =>'#333333'
                ],
                 // 预约结果
                 'keyword4' => [
                     'value' =>urlencode($data['examine_text']),
                     'color' =>'#333333'
                 ],
                 // 主要内容
                 'keyword5' => [
                     'value' =>urlencode($data['examine_reason']),
                     'color' =>'#333333'
                 ],
                 // 备注
                 'remark' => [
                    'value' =>urlencode($data['remark']),
                    'color' =>'#333333'
                 ],
            ]
        ];
        return $template;
    }

    // 客户预约通知【管理员接收】
    public function wx_gzh_admin_examine_template($openId,$data){
        if(empty($openId) || !isset($data['name']) ||!isset($data['mobile'])||!isset($data['subscribe_date'])||!isset($data['subscribe_text'])|| !isset($data['remark']) ) return false;
        $template = array(
            "touser" => "$openId",
            "template_id" => config('wx_gzh_admin_examine_template_id'),
//            'url' =>"https://archives.pfr.kim/index.php/web/wxLogin",
            'topcolor' => '#CCCCCC',
            'data' => array(
                'first'   => array(
                        'value' =>urlencode('管理员，你好！你有新的预约消息：'),
                        'color' => '#333333'
                ),
                // 客户姓名
                'keyword1' => array(
                    'value' =>urlencode($data['name']),
                    'color' =>'#333333'
                ),
                // 客户手机
                'keyword2' =>array(
                    'value' =>urlencode($data['mobile']),
                    'color' =>'#333333'
                ),
                // 预约时间
                'keyword3' => array(
                    'value' =>urlencode($data['subscribe_date']),
                    'color' =>'#333333'
                ),
                // 预约内容
                'keyword4' => array(
                    'value' =>urlencode($data['subscribe_text']),
                    'color' =>'#333333'
                ),
                // 备注
                'remark' => array(
                    'value' =>urlencode($data['remark']),
                    'color' =>'#333333'
                ),
            )
        );

        return $template;
    }
}
